<?php 
/***
    Amrita ITEWS - Copyright (C) 2009 Amrita Vishwa Vidyapeetham, Amritapuri.
                                     (http://www.amrita.edu)
    ***************************************************************************
    This file is part of the Amrita ITEWS distribution.
    Amrita ITEWS is free software; you can redistribute it and/or modify it 
    under the terms of the GNU General Public License (version 2) as published 
    by the Free Software Foundation AND MODIFIED BY the Amrita ITEWS exception.
    ***NOTE*** The exception to the GPL is included to allow you to distribute
    a combined work that includes Amrita ITEWS without being obliged to provide
    the source code for proprietary components outside of the Amrita ITEWS
    software. Amrita ITEWS is distributed in the hope that it will be useful, 
    but WITHOUT ANY WARRANTY; without even the implied warranty of 
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
    Public License for more details. You should have received a copy of the GNU
    General Public License and the Amrita ITEWS license exception along with 
    Amrita ITEWS if not then it can be viewed here: 
    http://itews.amrita.ac.in/license.html.
    
    Documentation, latest information, license and contact details are at:
    http://itews.amrita.ac.in/
 
    Amrita ITEWS source code can be found at:
    http://code.google.com/p/itews"; 
    
    The initial code-base of Amrita ITEWS was developed by Amrita Vishwa 
    Vidyapeetham as part of the project titled,\"Intelligent & Interactive 
    Telematics using Emerging Wireless Technologies for Transport Systems 
    (ITEWS)\" sponsored by Technology Information Forecasting and Assessment 
    Council (TIFAC), India.
***/
?><?php
class MediaPlansController extends AppController {

	var $name = 'MediaPlans';
	//var $name = 'RouteSchedules';
	var $uses = array('RouteSchedule', 'RouteNodeAssoc', 'MediaPlan', 'MediaPlanSlot', 'MediaInfo', 'Media', 'Trip');
	
	// Over riding cleanupData() function of appController
	function cleanupData() {
		
		$this->cleanUpFields();
		//$this->sanitizeData('MediaPlan');
		//$this->checkForeignKeys('MediaPlan');
		
	}
	
	function index() {
		
		list($order, $limit, $page) = $this->setupPagination('RouteSchedule');
		if(!is_array($routeSchedules = $this->RouteSchedule->findAll(array('RouteSchedule.route_schedule_status'=>1), NULL, NULL, $limit, $page))){
			$routeSchedules = array();
		}
		$this->set('routeSchedules', $routeSchedules);
		$this->render('../media_plans/index');
		/*
		$this->set('routeSchedules', $this->RouteSchedule->findAll(array('RouteSchedule.route_schedule_status'=>1)));
		echo $order;
		$this->set('routeSchedules', $this->RouteSchedule->findAll(NULL, NULL, $order, $limit, $page));
		 */
		
	}
	
	function view($id = null) {
		$this->checkRecordExistance($id, 'RouteSchedule');
		$this->MediaPlan->recursive = 2;
		$this->MediaPlanSlot->recursive = 3;
		if (!is_array($mediaPlanSlots = $this->MediaPlanSlot->findAll())) {
			$mediaPlanSlots = array();
		}
		$routeSchedules = array(); 
		$rsnaIds = array(); 
		foreach ($mediaPlanSlots as $mediaPlanSlot) {
			$routeScheduleId   = $mediaPlanSlot['MediaPlan']['RouteScheduleNodeAssoc']['RouteSchedule']['id'];
			if($routeScheduleId == $id) {
				$routeSchedules[] = $mediaPlanSlot; 			
				$rsnaIds[] = $mediaPlanSlot['MediaPlan']['RouteScheduleNodeAssoc']['id'];; 			
			}
		}
		$rsnaIds    = array_unique($rsnaIds);
		$rsnaIdList = implode(",", $rsnaIds);
		if (empty($rsnaIdList)) {
			$rsnaIdList = "0";
		}
		$routeId = $this->RouteSchedule->field('RouteSchedule.route_id', array('RouteSchedule.id'=>$id));
		$this->routeNodeAssocs = $this->RouteNodeAssoc->findAll(array('RouteNodeAssoc.route_id'=>$routeId), null, 'RouteNodeAssoc.sequence_no ASC');
		$conditions = array("MediaPlan.route_schedule_node_assoc_id IN ($rsnaIdList)");
		if (!is_array($mediaPlans = $this->MediaPlan->findAll($conditions))) {
			$mediaPlans = array();
		}
		usort($mediaPlans, array("MediaPlansController", "specialNodeSort"));
		$this->set('mediaPlans', $mediaPlans);
		$this->set('routeSchedule', $this->RouteSchedule->read(null, $id));
		$this->render('../media_plans/view');
		
	}

	function edit($id = null) {
		
		if (empty($this->data)) {
			$this->checkRecordExistance($id, 'RouteSchedule');
			$this->MediaPlan->recursive = 2;
//			$this->data = $this->MediaPlan->findall(array("RouteScheduleNodeAssoc.route_schedule_id"=>$id));
			$routeId = $this->RouteSchedule->field('RouteSchedule.route_id', array('RouteSchedule.id'=>$id));
			$this->routeNodeAssocs = $this->RouteNodeAssoc->findAll(array('RouteNodeAssoc.route_id'=>$routeId), null, 'RouteNodeAssoc.sequence_no ASC');
			$mediaPlans = $this->MediaPlan->findAll(array("RouteScheduleNodeAssoc.route_schedule_id"=>$id));
			usort($mediaPlans, array("MediaPlansController", "specialNodeSort")); 
			$this->data = $mediaPlans;
			$this->set('routeSchedule', $this->RouteSchedule->read(null, $id));
			$conditions = array('(Media.id != 1 AND Media.id != 2)');
			$order = array('media_title ASC');
 			$this->set('allMedias', $this->Media->findAll($conditions, null, $order));
 			$this->set('mediaPlanSlots', $this->MediaPlanSlot->findAll());
			$this->render('../media_plans/edit');
		} else {
			$this->cleanupData();
			$this->MediaPlan->begin();
			$this->MediaPlanSlot->begin();
			$this->MediaInfo->begin();
			$allowCommit = true;
			$mediaPlans = $this->MediaPlan->findAll(array("RouteScheduleNodeAssoc.route_schedule_id"=>$id));
			
			if (array_key_exists('MediaPlans', $this->data)) {
				if (is_array($this->data['MediaPlans'])) {
					foreach ($this->data['MediaPlans'] as $mediaPlan) {
						$mediaPlanData = $this->MediaPlan->find(array('MediaPlan.id'=>$mediaPlan['id']));
						/*
						$mediaPlan['MediaPlan']['id']                                = $mediaPlanData['MediaPlan']['id'];
						$mediaPlan['MediaPlan']['route_schedule_node_assoc_id']      = $mediaPlanData['MediaPlan']['route_schedule_node_assoc_id'];
						$mediaPlan['MediaPlan']['media_plan_code']                   = $mediaPlanData['MediaPlan']['media_plan_code'];
						$mediaPlan['MediaPlan']['media_plan_title']                  = $mediaPlanData['MediaPlan']['media_plan_title'];
						*/
						
						// Checking for presence of all neccessary fields

						if (up($mediaPlan['media_plan_initial_delay_condition'] == 'SA') && !array_key_exists('media_plan_initial_delay_value', $mediaPlan)) {
							$allowCommit = false;
							$this->Session->setFlash('Please corret following errors.', 'message_error');
							break;
						}
						
						$mediaPlanData['MediaPlan']['media_plan_trigger_condition']      = $mediaPlan['media_plan_trigger_condition'];
						$mediaPlanData['MediaPlan']['media_plan_initial_delay']          = (up($mediaPlan['media_plan_initial_delay_condition'] == 'SA')) ? $mediaPlan['media_plan_initial_delay_value'] : 0;
						$mediaPlanData['MediaPlan']['media_plan_intermediate_delay']     = $mediaPlan['media_plan_intermediate_delay'];
						$mediaPlanData['MediaPlan']['media_plan_loop_till_next_trigger'] = $mediaPlan['media_plan_loop_till_next_trigger'];
						$mediaPlanData['MediaPlan']['media_plan_loop_iteration_delay']   = $mediaPlan['media_plan_loop_iteration_delay'];
					//	$fieldList = array('media_plan_trigger_condition', 'media_plan_initial_delay', 'media_plan_intermediate_delay', 'media_plan_loop_till_next_trigger', 'media_plan_loop_iteration_delay');

						if ($this->MediaPlan->save($mediaPlanData)) {
							
							// Before saving new media plan slots erase existing records for this media plan
							$deleteOkflag = true;
							$oldMediaPlanSlots = $this->MediaPlanSlot->findAll(array('MediaPlanSlot.media_plan_id'=>$mediaPlan['id'], 'MediaPlanSlot.id'));
							foreach($oldMediaPlanSlots as $omps){
								if(!$this->MediaPlanSlot->del($omps['MediaPlanSlot']['id'])){
									$deleteOkflag= false;
									break;
								}
							}
							if (!$deleteOkflag) {
								$allowCommit = false;
								$this->Session->setFlash('Unable to update Media plan slots.', 'message_error');
								break;
							}
							// Save media plan slots here 
							unset($mediaPlanSlotData);
							if (array_key_exists('MediaPlanSlots', $mediaPlan)) {
								if(is_array($mediaPlan['MediaPlanSlots'])) {
									foreach ($mediaPlan['MediaPlanSlots'] as $mediaPlanSlot) {
										unset($mediaPlanSlotData);
										$mediaPlanSlotData['MediaPlanSlot']['id']                          = $mediaPlanSlot['id'];
										$mediaPlanSlotData['MediaPlanSlot']['media_plan_id']               = $mediaPlan['id'];
										$mediaPlanSlotData['MediaPlanSlot']['media_id']                    = $mediaPlanSlot['media_id'];
										$mediaPlanSlotData['MediaPlanSlot']['media_plan_slot_sequence_no'] = $mediaPlanSlot['media_plan_slot_sequence_no'];
										$mediaPlanSlotData['MediaPlanSlot']['media_plan_slot_duration']    = $mediaPlanSlot['media_plan_slot_duration'];
										if (!$this->MediaPlanSlot->save($mediaPlanSlotData)) {
											$allowCommit = false;
											$this->Session->setFlash('Unable to save Media plan slots.', 'message_error');
											break;
										}
									}
								}
							}
							
						} else {
							$allowCommit = false;
							$this->Session->setFlash('Unable to save Media plans.', 'message_error');
							break;
						}
					}
				} else {
					$allowCommit = false;
					$this->Session->setFlash('JavaScript Error. Unable to save Media plans. ', 'message_error');
				}
			} else {
				$allowCommit = false;
				$this->Session->setFlash('JavaScript Error. Unable to save Media plans.', 'message_error');
			}
			
			if($allowCommit) {
				// Create a media info entry only if route schedule is assigned to any vehicle
				if ($this->Trip->findCount(array('Trip.route_schedule_id'=>$id)) > 0) {
					if(!$this->pushToMediaInfoQueue($id)) {
						$allowCommit = false;
						$this->Session->setFlash('Error while updating media infos queue.', 'message_error');
					}
				}
			}
			/*
			$allowCommit = false;
			$this->Session->setFlash('Error test.', 'message_error');
			*/
			if($allowCommit) {
				$this->MediaPlan->commit();
				$this->MediaPlanSlot->commit();
				$this->MediaInfo->commit();
				$this->Session->setFlash('The Media plans have been saved.', 'message_ok');
				$this->redirect('/media_plans/index');
			} else {
				$this->MediaPlan->rollback();
				$this->MediaPlanSlot->rollback();
				$this->MediaInfo->rollback();
				$this->MediaPlan->recursive = 2;
				$this->data = $this->MediaPlan->findall(array("RouteScheduleNodeAssoc.route_schedule_id"=>$id));
				$this->set('routeSchedule', $this->RouteSchedule->read(null, $id));
				$conditions = array('(Media.id != 1 AND Media.id != 2)');
				$order = array('media_title ASC');
	 			$this->set('availableMedias', $this->Media->findall($conditions, null, $order));
				$this->render('../media_plans/edit');
			}
		}
	}

	/*
	function delete($id = null) {
		$this->checkRecordExistance($id);
		$this->MediaPlan->begin();
		$this->MediaInfo->begin();
		if ($this->MediaPlan->del($id)) {
			$this->MediaPlan->commit();
			$this->MediaInfo->commit();
			$this->Session->setFlash('The Media plan deleted.', 'message_ok');
			$this->redirect('/media_plans/index');
			
		} else {
			$this->MediaPlan->rollback();
			$this->MediaInfo->rollback();
			$this->showError(ERROR_DELETE, 'Unable to delete record.');
		}
	}
	*/
	
	function pushToMediaInfoQueue($referenceId) {
		
		$fields['media_info_type'] = "media_plan"; 
		$fields['media_info_reference'] = $referenceId;
		if ($this->MediaInfo->hasAny($fields)) {
			// Entry already exists; Just return
			return true;
		}
		$data['MediaInfo']['media_info_type'] = 'media_plan';
		$data['MediaInfo']['media_info_reference'] = $referenceId;
		if ($this->MediaInfo->save($data)) {
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * Enter description here...
	 *
	 * @param unknown_type $a
	 * @param unknown_type $b
	 * @return unknown
	 */
	function specialNodeSort($a, $b) {
		
		$nodeA = $a['RouteScheduleNodeAssoc']['node_id'];
		$nodeB = $b['RouteScheduleNodeAssoc']['node_id'];
		
		foreach ($this->routeNodeAssocs as $rna) {
			if ($nodeA == $rna['RouteNodeAssoc']['node_id']) {
				$sequenceNoOfA = $rna['RouteNodeAssoc']['sequence_no'];
			}
			if ($nodeB == $rna['RouteNodeAssoc']['node_id']) {
				$sequenceNoOfB = $rna['RouteNodeAssoc']['sequence_no'];
			}
		}
		
		if ($sequenceNoOfA >= $sequenceNoOfB) {
			return 1;
		} else {
			return -1;
		}
		
	}
	
}
?>
